﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


using iTextSharp.text.pdf;
using common_errCode;
using common_string;
using common_park;



namespace PDFTools_itext
{
    class PDFToolsModule
    {
        private PdfReader pdfReader;
        private string m_strSrcPdfName;
        private int m_errCode;

        private String m_strErrMsg;

        public PDFToolsModule()
        {
            pdfReader = null;
            m_strSrcPdfName = string.Empty;
            m_strErrMsg = string.Empty;
            m_errCode = ErrCode.S_OK;
        }

        /*
        public PDFToolsModule(string SrcPdfName, string ownerPassword)
        {
            pdfReader = null;
            m_strSrcPdfName = SrcPdfName;
            m_strErrMsg = string.Empty;

            pdfReader = new PdfReader(SrcPdfName, common_string.StringUtils.GetBytes(ownerPassword));
        }
        */

        public int SetPdfFile(string SrcPdfName, string ownerPassword = "")
        {
            isOpen();
            
            m_strSrcPdfName = SrcPdfName;

            if(!FileUtils.IsExistFile(SrcPdfName))
            {
                return ErrCode.ERR_PDFFILE_DOES_NOT_EXIST;
            }

            if (!pdfFileOpen(SrcPdfName, ownerPassword))
            {
                return ErrCode.ERR_PDFFILE_CANNOT_OPEN_FILE;
            }


            return ErrCode.S_OK;

        }


        ~PDFToolsModule()
        {
            isClosed();
        }

        private bool pdfFileOpen(string srcFile, string ownerPassword)
        {
            bool bRet = false;

            try
            {
                pdfReader = new PdfReader(SrcPdfName, common_string.StringUtils.GetBytes(ownerPassword));
                bRet = true;
            }
            catch(Exception ex)
            {
                m_strErrMsg = ex.ToString();
            }

            return bRet;
        }

        public bool GetPdfInfo()
        {
            try
            {
                Dictionary<string, string> info = pdfReader.Info;
                /*
                "Title" , Subject, Keywords, Creator
                */

                foreach (KeyValuePair<string, string> kvp in info)
                {
                    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                
            }

            return true;
        }

        private void isOpen()
        {
            try
            {
                if (pdfReader != null)
                {
                    pdfReader.Close();
                    pdfReader.Dispose();
                }
            }
            catch (Exception ex)
            {
                m_strErrMsg = ex.ToString();
            }
        }

        private bool isOpened()
        {
            return pdfReader != null ? true : false;
        }

        private bool isClosed()
        {
            bool bRet = false;
            try
            {
                if (pdfReader != null)
                {
                    pdfReader.Close();
                    pdfReader.Dispose();

                    bRet = true;
                }
            }
            catch (Exception ex)
            {
                m_strErrMsg = ex.ToString();
            }

            return bRet;
        }

        // 추가 작업 진행 되어야 함
        // 암호화 플래그 관련되어서 진행이 안되어 있음
        public int GetEncryptPdf(string dstPath, string userPassword, string ownerPassword, string flag)
        {
            if (!isOpened())
                return -1;

            using (Stream outPdfFile = new FileStream(dstPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                PdfEncryptor.Encrypt(pdfReader, outPdfFile, true, userPassword, ownerPassword, 
                    PdfWriter.ALLOW_SCREENREADERS);
            }
            
            return 0;
        }


        // 테스트 코드
        public int addOutline()
        {
            if (!isOpened())
                return -1;

            //isClosed();

            string dstPath = m_strSrcPdfName + "_outline.pdf";

            Stream outPdfFile = new FileStream(dstPath, FileMode.Create, FileAccess.Write, FileShare.None);


            PdfStamper pdfStamper = new PdfStamper(pdfReader, outPdfFile);

            List<Dictionary<string, object>> outlines = new List<Dictionary<string, object>>();
            Dictionary<string, object> map = new Dictionary<string, object>();
            outlines.Add(map);

            map.Add("Title", "test");
            map["Title"] = "테스트입니다.1";
            map["Action"] = "GoTo";
            map["Page"] = String.Format("{0} Fit", 1);


            //map.Add("Title1", "test1");

            Dictionary<string, object> map1 = new Dictionary<string, object>();
            outlines.Add(map1);
            map1["Title"] = "테스트입니다.2";
            map1["Action"] = "GoTo";
            map1["Page"] = String.Format("{0} Fit", 2);


           // map.Add("Title2", "test2");
            Dictionary<string, object> map2 = new Dictionary<string, object>();
            outlines.Add(map2);
            map2["Title"] = "테스트입니다.3";
            map2["Action"] = "GoTo";
            map2["Page"] = String.Format("{0} Fit",11);

            List<Dictionary<string, object>> kids = new List<Dictionary<string, object>>();
            map.Add("Kids", kids);
            
            Dictionary<string, object> kid = new Dictionary<string, object>();
            kids.Add(kid);
            kid["Title"] = "박세철";
            kid["Action"] = "GoTo";
            kid["Page"] = String.Format("{0} Fit", 3);


            Dictionary<string, object> kid1 = new Dictionary<string, object>();
            kids.Add(kid1);
            kid1["Title"] = "박세철2";
            kid1["Action"] = "GoTo";
            kid1["Page"] = String.Format("{0} Fit", 4);

            pdfStamper.Outlines = outlines;

            pdfStamper.Close();

            return 0;
        }


        private string ExtractText()
        {
            //PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
            //string txt = PdfTextExtractor.GetTextFromPage(pdfReader, 2, new LocationTextExtractionStrategy());
            //return txt;

            return "";
        }

        








        // get set 관련 내용은 아래 항목에서 처리하도록 한다.

        public string SrcPdfName
        {
            get { return m_strSrcPdfName; }
        }

        public String GetLastErrMessage
        {
            get { return m_strErrMsg; }
        }

        /////////////////////////////////////////////////////////////////////////
    }
}
